<template>
  <div class="container" v-loading="isLoading">
    <el-card>

      <template #header>
        <el-form inline :model="searchForm" ref="searchForm">
          <!-- <el-form-item label="标题">
            <el-input style="width:500px"
              v-model="searchForm.user"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item> -->
          <!-- <el-form-item>
            <el-button type="primary" @click="submitSearch">查询</el-button>
          </el-form-item> -->
        </el-form>
        <div class="table_tool">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="showAddOrEdit = true"
            >新增</el-button
          >
        </div>
      </template>

      <el-table :data="tableData" border>
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="投票标题" />
        <el-table-column prop="vote_type_id" label="是否多选">
          <template #default="{ row }">
            <div v-if="row.vote_type_id=='1'">单选</div>
            <div v-else>多选</div>
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="截止时间" />
        <el-table-column prop="subdistrict_name" label="选择小区" />
        <el-table-column prop="admin_user_name" label="投票发起人" />
        <el-table-column label="操作" width="300px" align="center">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              @click="editInfo(row)"
              >编辑投票信息</el-button
            >
            <el-button
              type="text"
              @click="editOption(row)"
              >编辑投票项</el-button
            >
            <el-button
              type="text"
              class="red"
              @click="deleteById(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <footer class="footer">
      <el-pagination
        background
        layout="total, sizes, pager, jumper"
        :current-page="pagination.page"
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="pagination.page_size"
        :total="tableTotal"
        @size-change="(val) => (pagination.page_size = val)"
        @current-change="(val) => (pagination.page = val)"
      />
    </footer>

    <el-dialog
      title="编辑投票信息"
      :visible.sync="showAddOrEdit"
      width="1400px"
      @closed="() => $refs['builingForm'].resetFields()"
    >
      <el-form
        :model="builingForm"
        ref="builingForm"
        label-width="7em"
      >
        <el-form-item prop="$id" hidden />

        <el-form-item  label="标题" prop="name">
          <el-input
            v-model="builingForm.name"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>

        <el-form-item class="span-2" label="结束时间" prop="end_time">
          <el-date-picker
            v-model="builingForm.end_time"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="date"
            placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          class="span-2"
          label="小区"
          prop="subdistrict"
        >
          <el-select v-model="builingForm.subdistrict_id">
            <el-option
              v-for="(oVal, oIdx) of communityList"
              :key="oIdx"
              v-bind="oVal"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="span-2" label="是否多选" prop="vote_type_id">
          <el-switch v-model="builingForm.vote_type_id"></el-switch>
        </el-form-item>

        <el-form-item label="简介" prop="description">
          <el-input
            v-model="builingForm.description"
            type="textarea"
            row="3"
            placeholder="请输入投票简介"
          ></el-input>
        </el-form-item>

        <el-form-item label="详情介绍" prop="content">
          <tinymce v-model="builingForm.content" height="300" />
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button
          type="primary"
          @click="EditInformation()"
          :loading="loading.update"
          >确 定</el-button
        >
      </template>
    </el-dialog>

    <el-dialog
      title="编辑投票项"
      :visible.sync="showEditOption"
      width="1400px"
      @closed="() => $refs['builingForm'].resetFields()"
    >
      <el-form
        :model="builingForm"
        ref="builingForm"
        label-width="7em"
      >

        <el-form-item prop="$id" hidden />

        <el-form-item
          class="option_item"
          :label="oIdx ? '' : '选项配置'"
          v-for="(oVal, oIdx) of builingForm.vote_options"
          :key="oIdx"
          :rules="{
            required: true,
            message: '选项不能为空',
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="oVal.name"
            placeholder="请输入选项内容"
            @change="oVal.isEdit = oVal.id"
          />
          <span class="ipt_tool">
            <i class="el-icon-plus" @click="addOption" />
          </span>
          <span class="ipt_tool">
            <i class="el-icon-delete" @click="removeOption(oIdx)" />
          </span>
        </el-form-item>


      </el-form>
      <template #footer>
        <el-button
          type="primary"
          @click="submitOption()"
          :loading="loading.update"
          >确 定</el-button
        >
      </template>
    </el-dialog>

  </div>
</template>

<script>
import API from "@/api";
import { table, addOrEdit } from "@/utils/mixins";
import Tinymce from "@/components/Tinymce";
import Upload from "@/components/Upload/SingleImage.vue";

export default {
  mixins: [table, addOrEdit],
  components: {
    Tinymce,
    Upload,
  },
  data: () => ({
    showEditOption:false,
    showAddOrEdit:false,
    isLoading: true,
    tableData:[],
    tableTotal: 0,
    isKey: false,
    searchForm: {
      page: 1, // 当前页码
      per_page: 10, // 每页条数
    },

    builingForm: {
      $id: '',
      name: "",
      end_time: "",
      content: "",
      subdistrict_id: '',
      vote_type_id:true,
      description:'',
      vote_options:[],
    },

    editBefore:[],
    communityList:[],
  }),

  created() {
    this.getList()
    API.getCommunityList().then(({data})=>{
      this.communityList=data.items.map(item=>{
        return {value:item.id,label:item.name}
      })
    })
  },
  methods: {

    getList(){
      this.isLoading=true
      API.getVoteList(this.searchForm)
        .then(({data}) => {
          this.tableData=data.items
          this.tableTotal=data.total
        }).catch((err) => {
          this.tableData=[]
          this.tableTotal=0
        }).finally(() =>{
          this.isLoading = false;
        })

    },

    // 分页
    changeSize(val){
      this.searchForm.per_page = val
      this.getList()
    },

    // 分页
    changeCurrent(val){
      this.searchForm.page = val
      this.getList()
    },

    addOption() {
      this.builingForm.vote_options.push({
        name: "",
      });
    },

    // 删除投票
    deleteById(id){
      let _that=this
      this.$confirm(`是否删除改条投票数据？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
      .then(() => {
        API.delVote(id)
        .then(({data}) => {
          this.$message.success("删除成功！");
        }).catch((err) => {
        }).finally(() =>{
          _that.getList()
        })
      })
      .catch(() => {
      });
    },

    // 移除投票项
    removeOption(index) {
      this.builingForm.vote_options.splice(index, 1);
    },

    // 编辑投票信息
    editInfo(obj){
      this.builingForm.$id=obj.id;
      this.builingForm.name=obj.name;
      this.builingForm.content=obj.content;
      this.builingForm.end_time=obj.end_time;
      this.builingForm.subdistrict_id=obj.subdistrict_id;
      this.builingForm.description=obj.description;
      this.builingForm.vote_type_id=obj.vote_type_id=='1'?false:true
      this.showAddOrEdit=true
    },

    // 查看投票选项
    editOption(obj){
      this.builingForm.$id=obj.id;
      this.editBefore=[...obj.vote_options]
      this.builingForm.vote_options=obj.vote_options.length?obj.vote_options:[{
        name:"请输入投票项"
      }];
      this.showEditOption=true
    },

    // 新增/编辑投票信息
    EditInformation(){
      if(!this.builingForm.name.trim()) return this.$message.error("标题不可为空~~");
      if(!this.builingForm.end_time.trim()) return this.$message.error("截止时间不可为空~~")
      if(!this.builingForm.subdistrict_id) return this.$message.error("请选择小区~~")
      if(!this.builingForm.description.trim()) return this.$message.error("简介~~")
      if(!this.builingForm.content.trim()) return this.$message.error("详情不可为空~~")

      let data={
        name:this.builingForm.name,
        end_time:this.builingForm.end_time,
        subdistrict_id:this.builingForm.subdistrict_id,
        content:this.builingForm.content,
        vote_type_id:this.builingForm.vote_type_id,
        description:this.builingForm.description,
        vote_type_id:this.builingForm.vote_type_id?"2":'1'
      }
      if(this.builingForm.$id){
        API.editVote(this.builingForm.$id,data)
        .then(({data}) => {
          this.$message.success("编辑成功！");
        }).catch((err) => {
        }).finally(() =>{
          this.resetForm()
          this.getList()
        })
      }else{
        API.addVote(data)
        .then(({data}) => {
          this.$message.success("新增成功！");
        }).catch((err) => {
        }).finally(() =>{
          this.resetForm()
          this.getList()
        })
      }
    },


    // 提交投票项
    submitOption(){
      let id=this.builingForm.$id
      let vote_options=this.builingForm.vote_options
      if(this.editBefore.length>0){
        for(let i=0;i<this.editBefore.length;i++){
          API.delVoteOption(this.editBefore[i].id)
          .then({}).catch((err) => {})
        }
      }


      if(vote_options.length>0){
        for(let i=0;i<vote_options.length;i++){
          API.editVoteOption(id,{name:vote_options[i].name})
          .then({}).catch((err) => {})
        }
      }
      this.resetForm()
      this.getList()
    },

    // 重置表单
    resetForm(){
      this.builingForm.name=""
      this.builingForm.end_time=""
      this.builingForm.content=""
      this.builingForm.subdistrict_id=""
      this.builingForm.vote_options=[{
        name:"请输入投票项"
      }];
      this.showAddOrEdit=false
      this.showEditOption=false
    },

    initInfoData({ source, row }) {
      API.getVoteOptionList({ vote: row.id })
        .then(({ data }) => {
          source.$backup = _.cloneDeep(data)
          source.$domains = data;
        })
        .catch((err) => {});
    },

    // 提交 新增/编辑
    submitRowData(formName, callBack = false) {
      let source = this[formName];
      // return false;
      this.$refs[formName]
        .validate()
        .then(() => {
          const keys = Object.keys(source).filter((k) => !k.startsWith("$"));
          const options = _.pick(source, keys);
          this.loading.update = true;
          if (_.has(source, "$image_uri")) {
            let formData = new FormData();
            for (const entries of Object.entries(options)) {
              formData.append(...entries);
            }
            return source.$id
              ? API[source.$action[1]](source.$id, formData)
              : API[source.$action[0]](formData);
          }
          return source.$id
            ? API[source.$action[1]](source.$id, options)
            : API[source.$action[0]](options);
          // return new Promise((resolve) => setTimeout(() => resolve(), 1000));
        })
        .then(({ data }) => {
          // 获取活动ID，在对选项操作
          let { $domains, $backup } = this.builingForm;
          let optionArr = _.partition($domains, "id");
          let delArr = _.differenceBy($backup, optionArr[0], "id");
          let editArr = _.filter(optionArr[0], "isEdit");
          let pAdd = optionArr[1].map((v) =>
            API.addVoteOption({
              vote: data.id,
              name: v.name,
            })
          );
          let pEdit = editArr.map((v) =>
            API.editVoteOption(v.id, {
              vote: data.id,
              name: v.name,
            })
          );
          let pDel = delArr.map((v) => API.delVoteOption(v.id));
          return Promise.all([...pAdd, ...pEdit, pDel]);
        })
        .then(() => {
          if (source.$show) this[source.$show] = false;
          else this.showAddOrEdit = false;
          if (source.$id) {
            this.$message.success("编辑成功！");
          } else {
            this.$message.success("新增成功！");
          }
          if (callBack) callBack();
          else this.fetchData(1);
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          this.loading.update = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.option_item {
  .ipt_tool {
    margin-left: 16px;
  }
}
::v-deep {
    .el-input {
      width: 80%;
    }
    .el-switch{
      transform:translateY(6px)
    }
    .el-message-box{
      min-width:400px;
    }
    .el-dialog{
      margin-top:2vh !important;
    }
    .el-input .el-input__inner{
      border-radius:4px !important;
    }
    .el-message-box__message{
      position: absolute !important;
      top:50% !important;
      left:40px !important;
    }
    .el-form-item__label{
      font-size:16px !important;
    }
  }
</style>
